#include "AudioEngine.hpp"
#include "malloc.h"

AudioEngine::AudioEngine(unsigned int f, unsigned short c, unsigned int r) : channels(c), samplerate(r), position(0), state(ENGINE_STOPPED) {
    size=sizeof(float)*c*f;
    buffer=(float*)malloc(size);
    queue=QQueue<AudioFile*>();
}

AudioEngine::~AudioEngine() {
    free(buffer);
}

int AudioEngine::fillOutputBuffer(float* output, unsigned int length) {
    if(state==ENGINE_PAUSED) { //playback is paused so we provide no sound
        for(unsigned int i=0; i<length; i++) output[i]=0;
        return length;
    }
    for(unsigned int i=0; i<length; i++, position++) {
        if(position==size) position=0; //position reached the end of the buffer
        output[i]=buffer[position];
    }
    return -1;
}

void AudioEngine::seekFrame(unsigned int f) {

}

void AudioEngine::seekTime(unsigned int ms) {

}

void AudioEngine::playImmediatetly(AudioFile *af) {
    queue.clear();
    queue.enqueue(af);
    position=0;
}
void AudioEngine::nextFile(AudioFile *af) {
    queue.enqueue(af);
}

void AudioEngine::togglePause() {
    //paused=!paused;
    if(state==ENGINE_PLAYING) state=ENGINE_PAUSED;
    else state=ENGINE_PLAYING;
}

void AudioEngine::stop() {
    position=0;
    state=ENGINE_STOPPED;
    //paused=true;
}

void AudioEngine::play() {
    state=ENGINE_PLAYING;
}

void AudioEngine::run() {

}
